<template>
  <div class="recognition-statistics-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>识别统计分析</span>
          <div>
            <el-dropdown @command="handleExport" split-button type="primary" @click="refreshData">
              刷新数据
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="basic">导出基础统计</el-dropdown-item>
                  <el-dropdown-item command="detailed">导出详细记录</el-dropdown-item>
                  <el-dropdown-item command="user_stats">导出用户统计</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
      
      <div v-loading="loading">
        <div class="filter-box">
          <el-form :inline="true" :model="queryParams">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                @change="handleDateChange"
              />
            </el-form-item>
            <el-form-item label="识别类型">
              <el-select v-model="queryParams.recognition_type" placeholder="请选择类型" clearable @change="handleQuery">
                <el-option label="全部类型" value="" />
                <el-option label="人脸识别" value="face" />
                <el-option label="身份证" value="id_card" />
                <el-option label="驾驶证" value="drive_license" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间维度">
              <el-radio-group v-model="queryParams.time_dimension" @change="handleQuery">
                <el-radio-button label="day">按天</el-radio-button>
                <el-radio-button label="week">按周</el-radio-button>
                <el-radio-button label="month">按月</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <div class="stat-overview">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">总识别次数</div>
                <div class="stat-value">{{ statistics.total_count || 0 }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">成功次数</div>
                <div class="stat-value success">{{ statistics.success_count || 0 }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">失败次数</div>
                <div class="stat-value failed">{{ statistics.failed_count || 0 }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">成功率</div>
                <div class="stat-value">{{ statistics.success_rate || 0 }}%</div>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <el-divider content-position="left">识别趋势分析</el-divider>
        
        <div class="chart-container" v-if="statistics.time_series && statistics.time_series.length > 0">
          <div ref="dailyChart" class="chart"></div>
        </div>
        <el-empty v-else description="暂无数据" />
        
        <el-divider content-position="left">识别类型分布</el-divider>
        
        <div class="chart-container" v-if="statistics.type_distribution && statistics.type_distribution.length > 0">
          <el-row :gutter="20">
            <el-col :span="12">
              <div ref="typeChart" class="chart pie-chart"></div>
            </el-col>
            <el-col :span="12">
              <div class="chart-table">
                <el-table :data="statistics.type_distribution" border>
                  <el-table-column prop="type" label="识别类型">
                    <template #default="scope">
                      <el-tag :type="getTypeTagType(scope.row.type)">
                        {{ getRecognitionTypeName(scope.row.type) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="count" label="次数" />
                  <el-table-column prop="percentage" label="占比">
                    <template #default="scope">
                      {{ scope.row.percentage }}%
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-empty v-else description="暂无数据" />
        
        <el-divider content-position="left">设备分布</el-divider>
        
        <div class="chart-container" v-if="statistics.device_distribution && statistics.device_distribution.length > 0">
          <el-row :gutter="20">
            <el-col :span="12">
              <div ref="deviceChart" class="chart pie-chart"></div>
            </el-col>
            <el-col :span="12">
              <div class="chart-table">
                <el-table :data="statistics.device_distribution" border>
                  <el-table-column prop="device" label="设备类型" />
                  <el-table-column prop="count" label="次数" />
                  <el-table-column prop="percentage" label="占比">
                    <template #default="scope">
                      {{ scope.row.percentage }}%
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-empty v-else description="暂无数据" />
        
        <el-divider content-position="left">活跃用户TOP10</el-divider>
        
        <div class="chart-container" v-if="statistics.top_users && statistics.top_users.length > 0">
          <el-table :data="statistics.top_users" border>
            <el-table-column type="index" label="排名" width="80" />
            <el-table-column prop="user_id" label="用户ID" width="100" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="count" label="识别总次数" />
            <el-table-column prop="success_count" label="成功次数" />
            <el-table-column prop="success_rate" label="成功率">
              <template #default="scope">
                <div style="display: flex; align-items: center;">
                  <el-progress 
                    :percentage="scope.row.success_rate" 
                    :stroke-width="15" 
                    :color="getSuccessRateColor(scope.row.success_rate)"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-empty v-else description="暂无数据" />
        
        <el-divider content-position="left">每日识别前十用户</el-divider>
        
        <div class="chart-container">
          <div class="daily-users-header">
            <el-form :inline="true">
              <el-form-item label="选择日期">
                <el-date-picker
                  v-model="dailyDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                  :disabled-date="disableFutureDate"
                  @change="handleDailyDateChange"
                />
              </el-form-item>
            </el-form>
            <span class="daily-date-display" v-if="dailyDate">{{ dailyDate }} 用户识别排行</span>
          </div>
          
          <div v-if="statistics.daily_top_users && statistics.daily_top_users.length > 0" class="daily-users-split">
            <div class="left-panel">
              <div ref="dailyUserChart" class="daily-users-chart"></div>
            </div>
            <div class="right-panel">
              <el-table :data="statistics.daily_top_users" border stripe highlight-current-row>
                <el-table-column type="index" label="排名" width="80">
                  <template #default="scope">
                    <div class="rank-cell">
                      <el-tag v-if="scope.$index < 3" :type="getRankTagType(scope.$index)" class="rank-tag">{{ scope.$index + 1 }}</el-tag>
                      <span v-else>{{ scope.$index + 1 }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="user_id" label="用户ID" width="80" />
                <el-table-column prop="username" label="用户名" />
                <el-table-column prop="count" label="识别次数" sortable />
                <el-table-column prop="percentage" label="占比" sortable>
                  <template #default="scope">
                    <div style="display: flex; align-items: center;">
                      <span style="margin-right: 10px;">{{ scope.row.percentage }}%</span>
                      <el-progress 
                        :percentage="scope.row.percentage" 
                        :stroke-width="10" 
                        :show-text="false"
                        :color="getPercentageColor(scope.row.percentage)"
                      />
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <el-empty v-else description="暂无数据" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getRecognitionStatistics, exportRecognitionStatistics } from '@/api/recognition-records'

const loading = ref(false)
const statistics = ref({})
const dateRange = ref([])
const dailyDate = ref(new Date().toISOString().split('T')[0]) // 默认为今天
const dailyChart = ref(null)
const typeChart = ref(null)
const deviceChart = ref(null)
const dailyUserChart = ref(null)
let dailyChartInstance = null
let typeChartInstance = null
let deviceChartInstance = null
let dailyUserChartInstance = null

const queryParams = reactive({
  recognition_type: '',
  start_date: '',
  end_date: '',
  time_dimension: 'day'
})

// 获取统计数据
const getStatistics = async () => {
  loading.value = true
  try {
    const res = await getRecognitionStatistics(queryParams)
    if (res.code === 0) {
      statistics.value = res.data
      
      nextTick(() => {
        initDailyChart()
        initTypeChart()
        initDeviceChart()
        initDailyUserChart()
      })
    } else {
      ElMessage.error(res.message || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  getStatistics()
}

// 重置查询
const resetQuery = () => {
  queryParams.recognition_type = ''
  queryParams.start_date = ''
  queryParams.end_date = ''
  queryParams.time_dimension = 'day'
  dateRange.value = []
  handleQuery()
}

// 日期范围变化
const handleDateChange = (val) => {
  if (val) {
    queryParams.start_date = val[0]
    queryParams.end_date = val[1]
  } else {
    queryParams.start_date = ''
    queryParams.end_date = ''
  }
  
  handleQuery()
}

// 每日用户统计日期变化
const handleDailyDateChange = (val) => {
  if (val) {
    getDailyTopUsers(val)
  }
}

// 禁用未来日期
const disableFutureDate = (time) => {
  return time.getTime() > Date.now()
}

// 获取每日前十用户
const getDailyTopUsers = async (date) => {
  loading.value = true
  try {
    const res = await getRecognitionStatistics({
      date: date,
      top_users_type: 'daily'
    })
    if (res.code === 0 && res.data.daily_top_users) {
      // 确保数据按识别次数降序排列
      statistics.value.daily_top_users = res.data.daily_top_users.sort((a, b) => b.count - a.count);
      
      // 计算每个用户在总识别量中的占比
      const totalCount = statistics.value.daily_top_users.reduce((sum, user) => sum + user.count, 0);
      statistics.value.daily_top_users = statistics.value.daily_top_users.map(user => {
        return {
          ...user,
          percentage: totalCount ? Number(((user.count / totalCount) * 100).toFixed(2)) : 0
        };
      });
      
      // 等待DOM更新后初始化图表
      nextTick(() => {
        initDailyUserChart();
      });
    } else {
      statistics.value.daily_top_users = []
      ElMessage.warning('该日期没有用户识别数据')
    }
  } catch (error) {
    console.error('获取每日用户统计失败', error)
    ElMessage.error('获取每日用户统计失败')
    statistics.value.daily_top_users = []
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  handleQuery()
}

// 初始化日常趋势图表
const initDailyChart = () => {
  if (!statistics.value.time_series || statistics.value.time_series.length === 0) return
  
  if (!dailyChartInstance) {
    dailyChartInstance = echarts.init(dailyChart.value)
  }
  
  const dates = statistics.value.time_series.map(item => item.time_display || item.time_id)
  const counts = statistics.value.time_series.map(item => item.count)
  const successRates = statistics.value.time_series.map(item => item.success_rate)
  
  const option = {
    title: {
      text: '识别趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['识别次数', '成功率'],
      bottom: 10
    },
    xAxis: [
      {
        type: 'category',
        data: dates,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '识别次数',
        min: 0,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '成功率(%)',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '识别次数',
        type: 'bar',
        data: counts,
        barWidth: 20,
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '成功率',
        type: 'line',
        yAxisIndex: 1,
        data: successRates,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  }
  
  dailyChartInstance.setOption(option)
}

// 初始化类型分布图表
const initTypeChart = () => {
  if (!statistics.value.type_distribution || statistics.value.type_distribution.length === 0) return
  
  if (!typeChartInstance) {
    typeChartInstance = echarts.init(typeChart.value)
  }
  
  const data = statistics.value.type_distribution.map(item => {
    return {
      name: getRecognitionTypeName(item.type),
      value: item.count
    }
  })
  
  const option = {
    title: {
      text: '识别类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      top: 'center',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '识别类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data,
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C']
      }
    ]
  }
  
  typeChartInstance.setOption(option)
}

// 初始化设备分布图表
const initDeviceChart = () => {
  if (!statistics.value.device_distribution || statistics.value.device_distribution.length === 0) return
  
  if (!deviceChartInstance) {
    deviceChartInstance = echarts.init(deviceChart.value)
  }
  
  const data = statistics.value.device_distribution.map(item => {
    return {
      name: item.device,
      value: item.count
    }
  })
  
  const option = {
    title: {
      text: '设备分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      top: 'center',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '设备分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data,
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C']
      }
    ]
  }
  
  deviceChartInstance.setOption(option)
}

// 初始化每日用户排名图表
const initDailyUserChart = () => {
  if (!statistics.value.daily_top_users || statistics.value.daily_top_users.length === 0) return
  
  if (!dailyUserChartInstance) {
    dailyUserChartInstance = echarts.init(dailyUserChart.value)
  }
  
  // 限制最多显示10个用户
  const topUsers = statistics.value.daily_top_users.slice(0, 10)
  
  const usernames = topUsers.map(item => item.username)
  const counts = topUsers.map(item => item.count)
  const percentages = topUsers.map(item => item.percentage)
  
  const option = {
    title: {
      text: '每日用户识别排名',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const data = params[0];
        return `${data.name}: ${data.value}次 (${percentages[data.dataIndex]}%)`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: usernames,
      inverse: true,
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        formatter: function(value, index) {
          // 给前三名添加特殊标记
          if (index < 3) {
            const marks = ['🥇', '🥈', '🥉'];
            return marks[index] + ' ' + value;
          }
          return value;
        }
      }
    },
    series: [
      {
        name: '识别次数',
        type: 'bar',
        data: counts,
        label: {
          show: true,
          position: 'right',
          formatter: '{c} 次'
        },
        itemStyle: {
          color: function(params) {
            // 为不同排名设置不同颜色
            const colors = ['#67C23A', '#E6A23C', '#F56C6C', '#409EFF', '#909399'];
            return params.dataIndex < colors.length ? colors[params.dataIndex] : '#409EFF';
          },
          borderRadius: [0, 4, 4, 0]
        }
      }
    ]
  };
  
  dailyUserChartInstance.setOption(option)
}

// 页面大小改变时重绘图表
window.addEventListener('resize', () => {
  if (dailyChartInstance) {
    dailyChartInstance.resize()
  }
  if (typeChartInstance) {
    typeChartInstance.resize()
  }
  if (deviceChartInstance) {
    deviceChartInstance.resize()
  }
  if (dailyUserChartInstance) {
    dailyUserChartInstance.resize()
  }
})

// 获取识别类型名称
const getRecognitionTypeName = (type) => {
  const typeMap = {
    'face': '人脸识别',
    'id_card': '身份证',
    'drive_license': '驾驶证'
  }
  return typeMap[type] || '未知'
}

// 获取类型标签样式
const getTypeTagType = (type) => {
  const typeMap = {
    'face': 'primary',
    'id_card': 'success',
    'drive_license': 'warning'
  }
  return typeMap[type] || ''
}

// 获取成功率颜色
const getSuccessRateColor = (success_rate) => {
  if (success_rate >= 90) {
    return '#67C23A'
  } else if (success_rate >= 70) {
    return '#E6A23C'
  } else {
    return '#F56C6C'
  }
}

// 获取排名标签类型
const getRankTagType = (index) => {
  const typeMap = {
    0: 'success',
    1: 'warning',
    2: 'danger'
  }
  return typeMap[index] || ''
}

// 获取百分比颜色
const getPercentageColor = (percentage) => {
  if (percentage >= 90) {
    return '#67C23A'
  } else if (percentage >= 70) {
    return '#E6A23C'
  } else {
    return '#F56C6C'
  }
}

// 导出统计数据
const handleExport = (command) => {
  // 构建导出参数
  const exportParams = {
    ...queryParams,
    export_type: command
  }
  
  // 获取导出URL
  const exportUrl = exportRecognitionStatistics(exportParams)
  
  // 创建隐藏的a标签并模拟点击下载
  const link = document.createElement('a')
  link.href = exportUrl
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('导出请求已发送，请稍候...')
}

onMounted(() => {
  getStatistics()
  getDailyTopUsers(dailyDate.value)
})
</script>

<style scoped>
.recognition-statistics-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-box {
  margin-bottom: 20px;
}

.stat-overview {
  margin: 20px 0;
}

.stat-card {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-value.success {
  color: #67C23A;
}

.stat-value.failed {
  color: #F56C6C;
}

.chart-container {
  margin: 20px 0;
}

.chart {
  height: 400px;
  width: 100%;
}

.pie-chart {
  height: 300px;
}

.chart-table {
  height: 300px;
  overflow-y: auto;
}

.el-divider {
  margin: 30px 0;
}

:deep(.el-progress-bar__outer) {
  border-radius: 8px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.daily-users-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.daily-date-display {
  font-size: 14px;
  color: #606266;
  font-weight: bold;
}

.rank-cell {
  display: flex;
  align-items: center;
}

.rank-tag {
  margin-right: 5px;
  font-weight: bold;
}

.daily-users-chart {
  height: 300px;
  margin-top: 20px;
  margin-bottom: 20px;
}

.daily-users-split {
  display: flex;
  justify-content: space-between;
}

.daily-users-split .left-panel {
  width: 60%;
}

.daily-users-split .right-panel {
  width: 38%;
}
</style> 